<!--
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-24 16:36:43
 * @LastEditTime: 2023-08-11 17:48:56
-->
<script lang="ts" setup name="ApprovalNodeConfig">
import { computed, reactive } from 'vue'
import OrgItems from '@main/views/approve-workflow/WorkFlow/OrgItems.vue'
import { Plus } from '@element-plus/icons-vue'
import { IkingPicker } from 'iking-web-ui'
import {
  EApprovalEmpty,
  EApproveCategory,
  EApproveType,
  ESelectRange
} from '@main/views/approve-workflow/enum'
import { useApproveObject } from './useApproveObject'
// const props = defineProps({
//   config: {
//     type: Object,
//     default: () => {}
//   }
// })

const flowStore = useFlowStore()
const {
  // ApprovalReject,
  EConfigType,
  MultipleSignature,
  ApproveCategory,
  ApproveType,
  SelectRange,
  orgPickerShow,
  pickState,
  ApprovalEmpty,
  pickerTitle,
  selectUser,
  selectNoSetUser,
  selectRole,
  handSelectRoleUser,
  pickerValue
} = useApproveObject()

const { baseUrl } = useHttpUrl()
const token = useToken()

const state = reactive({
  showOrgSelect: false,
  orgPickerSelected: [],
  orgPickerType: 'user',
  approval: {
    types: Object.entries(EApproveType).map(([name, value]) => {
      return {
        name,
        value
      }
    }),
    objTypes: Object.entries(EApproveCategory).map(([name, type]) => {
      return {
        name,
        type
      }
    }),
    scopeType: Object.entries(ESelectRange).map(([name, type]) => {
      return {
        name,
        type
      }
    }),
    approvalEmpty: Object.entries(EApprovalEmpty).map(([name, type]) => {
      return {
        name,
        type
      }
    })
    //   [
    //   { name: "指定人员", type: "ASSIGN_USER" },
    //   { name: "发起人自选", type: "SELF_SELECT" },
    //   { name: "连续多级主管", type: "LEADER_TOP" },
    //   { name: "主管", type: "LEADER" },
    //   { name: "角色", type: "ROLE" },
    //   { name: "发起人自己", type: "SELF" },
    //   { name: "表单内联系人", type: "FORM_USER" },
    // ],
  }
})

const nodeProps = computed(() => {
  return flowStore.selectedNode.props
})

const forms = computed(() => {
  // DEPT_PICKER,ORGANIZATION_PICKER,USER_PICKER
  return flowStore.design.formItems
    .filter((f: { distinguishType: string; widgetType: string; }) => {
      return f?.distinguishType === 'contacts' || f?.widgetType === 'USER_PICKER'
    })
    .map((v: any) => {
      return {
        ...v,
        id: v?.widgetName || v?.id,
        title: v?.options?.label || v?.widgetName || v?.widgetLabel
      }
    })
})
const formDeps = computed(() =>
  flowStore.design.formItems
    .filter((f: { distinguishType: string; widgetType: string; }) => {
      return f.distinguishType === 'departments' || f?.widgetType === 'DEPT_PICKER'
    })
    .map((v: any) => {
      return {
        ...v,
        id: v?.widgetName || v?.id,
        title: v?.options?.label || v?.widgetName || v?.widgetLabel
      }
    })
)

const formOrgs = computed(() =>
  flowStore.design.formItems
    .filter((f: { distinguishType: string; widgetType: string; }) => {
      return f.distinguishType === 'organization' || f?.widgetType === 'ORGANIZATION_PICKER'
    })
    .map((v: any) => {
      return {
        ...v,
        id: v?.widgetName || v?.id,
        title: v?.options?.label || v?.widgetName || v?.widgetLabel
      }
    })
)

// const pickerTitle = computed(() => {
//   switch (state.orgPickerType) {
//     case 'user':
//       return '请选择人员'
//     case 'role':
//       return '请选择系统角色'
//     default:
//       return null
//   }
// })
// const nodeOptions = computed(() => {
//   const values: any[] = []
//   const excType = [
//     'ROOT',
//     'EMPTY',
//     'CONDITION',
//     'CONDITIONS',
//     'BRANCH',
//     'CONCURRENTS'
//   ]
//   flowStore.nodeMap.forEach(v => {
//     if (!excType.includes(v.type))
//       values.push({ id: v.id, name: v.name })
//   })
//   return values
// })
const showMode = computed(() => {
  switch (nodeProps.value.approvalCategory) {
    case EApproveCategory.指定成员:
      return nodeProps.value.assignedUser.length > 1
    case EApproveCategory.发起人自选:
      return nodeProps.value.selfSelect.multiple
    case EApproveCategory.发起人部门主管:
    case EApproveCategory.联系人控件关联成员:
    case EApproveCategory.指定角色:
    case EApproveCategory.部门控件关联角色:
    case EApproveCategory.组织控件关联角色:
      return true
    default:
      return false
  }
})

const showApproveEmpty = computed(() => {
  switch (nodeProps.value.approvalCategory) {
    case EApproveCategory.指定成员:
    case EApproveCategory.发起人自己:
      return false
    case EApproveCategory.发起人自选:
      return (
        nodeProps.value.initiatorSpecifiedScopeType === ESelectRange.按角色指定
      )
    default:
      return true
  }
})

// const selected = (sel: any[]) => {
//   state.orgPickerSelected.length = 0
//   sel.forEach((val: any) => state.orgPickerSelected.push(val))
// }
// const removeOrgItem = (index: any) => {
//   select.value.splice(index, 1)
// }

// picker组件确定后
const handSelectPicker = (val: any) => {
  if (pickState.type === EConfigType.对象)
    nodeProps.value.assignedUser = val.list
  else if (pickState.type === EConfigType.为空时)
    nodeProps.value.reserveApprovals = val.list
}

// 选择范围更改后，需要重置已选对象
watch(
  () => [
    nodeProps.value.approvalCategory,
    nodeProps.value.initiatorSpecifiedScopeType
  ],
  () => {
    nodeProps.value.assignedUser = []
    pickerValue.value = []
  }
)

watch(() => nodeProps.value.approveType, () => {
  nodeProps.value.assignedUser = []
  pickerValue.value = []
})
</script>

<template>
  <el-form label-position="top" label-width="90px">
    <el-form-item prop="text" class="user-type">
      <template #label>
        <span class="ikflow-flow-config-label">审批方式</span>
      </template>
      <el-radio-group v-model="nodeProps.approveType" class="ikflow-flow-radio">
        <el-radio v-for="t in state.approval.types" :key="t.value" :label="t.value">
          {{ t.name }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <template v-if="nodeProps.approveType === ApproveType.人工审批">
      <el-form-item label="⚙ 审批对象" prop="text" class="user-type">
        <template #label>
          <span class="ikflow-flow-config-label">审批对象</span>
        </template>
        <el-radio-group v-model="nodeProps.approvalCategory" class="ikflow-flow-radio">
          <el-radio v-for="t in state.approval.objTypes" :key="t.type" :label="t.type">
            {{ t.name }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-divider v-if="nodeProps.approvalCategory !== ApproveCategory.发起人部门主管" class="!m-0" />
      <template v-if="nodeProps.approvalCategory === ApproveCategory.指定成员">
        <el-form-item label="⚙ 添加成员  最多不能超过20人" prop="text" class="user-type">
          <template #label>
            <span class="ikflow-flow-config-label">
              添加成员
              <span class="info">最多不能超过20人</span>
            </span>
          </template>
          <div>
            <OrgItems v-model="nodeProps.assignedUser" />

            <el-button
              size="small"
              :icon="Plus"
              type="primary"
              @click="selectUser"
            >
              选择人员
            </el-button>
            <IkingPicker
              ref="refIkingPicker"
              v-model="nodeProps.assignedUser"
              v-model:show="state.showOrgSelect"
              :title="pickerTitle"
              :api="{
                methods: 'post',
                url: `${baseUrl}/server/component/pick/mix`,
                headers: {
                  'Content-Type': 'application/json;charset=UTF-8',
                  'Authorization': token,
                },
              }"
              :tabs="['group']"
              :type-option="{
                dep: 'DEPT',
                user: 'USER',
                role: 'ROLE',
                post: 'POST',
              }"
              :prop-option="{
                name: 'elementName',
                id: 'elementId',
                type: 'elementType',
              }"
            />
          </div>
        </el-form-item>
        <el-divider class="!m-0" />
        <el-form-item label="多人审批方式" prop="text" class="approve-mode">
          <template #label>
            <span class="ikflow-flow-config-label">多人审批方式 </span>
          </template>
          <el-radio-group v-model="nodeProps.mode">
            <el-radio :label="MultipleSignature.依次审批" class="w-full">
              依次审批（按顺序依次审批）
            </el-radio>
            <el-radio :label="MultipleSignature.会签" class="w-full">
              会签（须所有审批人同意）
            </el-radio>
            <el-radio :label="MultipleSignature.或签" class="w-full">
              或签（一名审批人同意或拒绝即可）
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
      <!-- <div v-else-if="nodeProps.approvalCategory === ApproveCategory.发起人部门主管">
        <el-divider />
        <el-form-item label="审批终点" prop="text" class="approve-end">
          <el-radio-group
            class="ikflow-flow-radio"
            v-model="nodeProps.leaderTop.endCondition"
          >
            <el-radio label="TOP">直到最上层主管</el-radio>
            <el-radio label="LEAVE">不超过发起人的</el-radio>
          </el-radio-group>
          <div
            class="approve-end-leave"
            v-if="nodeProps.leaderTop.endCondition === 'LEAVE'"
          >
            <span>第 </span>
            <el-input-number
              :min="1"
              :max="20"
              :step="1"
              size="small"
              v-model="nodeProps.leaderTop.level"
            />
            <span> 级主管</span>
          </div>
        </el-form-item>
      </div> -->
      <template v-else-if="nodeProps.approvalCategory === ApproveCategory.发起人自选">
        <el-form-item label="⚙ 选择范围" prop="initiatorSpecifiedScopeType" class="user-type">
          <template #label>
            <span class="ikflow-flow-config-label">选择范围</span>
          </template>
          <el-radio-group v-model="nodeProps.initiatorSpecifiedScopeType" class="ikflow-flow-radio">
            <el-radio v-for="t in state.approval.scopeType" :key="t.type" :label="t.type">
              {{ t.name }}
              <!-- <el-button
                v-if="
                  nodeProps.initiatorSpecifiedScopeType
                    !== SelectRange.全公司
                    && nodeProps.initiatorSpecifiedScopeType === t.type
                "
                text
                type="primary"
                class="inline-edit"
                @click="handSelectRoleUser(t)"
              >
                {{ nodeProps.assignedUser?.length ? '修改' : '添加' }}
              </el-button> -->
              <IkSvgIcon
                v-if="nodeProps.initiatorSpecifiedScopeType !== SelectRange.全公司 && nodeProps.initiatorSpecifiedScopeType === t.type"
                name="iksvg_bianji"
                class="ml-[4px]"
                pop
                :title="`选择${t.type === ESelectRange.按成员指定 ? '人员' : '角色'}`"
                @click="handSelectRoleUser(t)"
              />
            </el-radio>
          </el-radio-group>

          <OrgItems v-model="nodeProps.assignedUser" />
        </el-form-item>
        <el-form-item prop="selfSelect.multiple">
          <template #label>
            <span class="ikflow-flow-config-label">选人方式</span>
          </template>
          <el-radio-group v-model="nodeProps.selfSelect.multiple" class="ikflow-flow-radio">
            <el-radio :label="false">自选一个人</el-radio>
            <el-radio :label="true">自选多个人</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
      <!-- <div
        v-else-if="
          nodeProps.approvalCategory === ApproveCategory.发起人部门主管
        "
      >
        <el-divider />
        <el-form-item label="指定主管" prop="text">
          <span>发起人的第 </span>
          <el-input-number
            :min="1"
            :max="20"
            :step="1"
            size="small"
            v-model="nodeProps.leader.level"
          ></el-input-number>
          <span> 级主管</span>
          <div style="color: #409eff; font-size: small">
            👉 直接主管为 第 1 级主管
          </div>
        </el-form-item>
      </div> -->
      <div v-else-if="nodeProps.approvalCategory === ApproveCategory.指定角色">
        <el-form-item label="选择角色" prop="text" class="line-mode">
          <template #label>
            <span class="ikflow-flow-config-label">选择角色</span>
          </template>
          <div class="flex flex-col w-[80%]">
            <el-button :icon="Plus" type="primary" @click="selectRole">
              选择角色
            </el-button>
            <OrgItems v-model="nodeProps.assignedUser" />
          </div>
        </el-form-item>
      </div>
      <div
        v-else-if="nodeProps.approvalCategory === ApproveCategory.联系人控件关联成员
        "
      >
        <el-form-item label="选择联系人控件" prop="text" class="approve-end">
          <template #label>
            <span class="ikflow-flow-config-label">选择联系人控件</span>
          </template>
          <el-select
            v-model="nodeProps.formUser"
            clearable
            style="width: 80%;"
            placeholder="请选择包含联系人控件的表单项"
          >
            <el-option
              v-for="(op, index) in forms"
              :key="index"
              :label="op.title"
              :value="op.id"
            />
          </el-select>
        </el-form-item>
      </div>
      <div v-else-if="nodeProps.approvalCategory === ApproveCategory.部门控件关联角色">
        <el-form-item label="选择部门控件" prop="text" class="approve-end">
          <template #label>
            <span class="ikflow-flow-config-label">选择部门控件</span>
          </template>
          <div class="flex flex-col w-full">
            <el-select
              v-model="nodeProps.formDep"
              clearable
              style="width: 80%;"
              placeholder="请选择包含部门控件的表单项"
            >
              <el-option
                v-for="(op, index) in formDeps"
                :key="index"
                :label="op.title"
                :value="op.id"
              />
            </el-select>
            <div class="flex flex-col w-[80%]">
              <el-button
                :icon="Plus"
                class="mt-[8px]"
                type="primary"
                @click="selectRole"
              >
                选择角色
              </el-button>
              <OrgItems v-model="nodeProps.assignedUser" />
            </div>
          </div>
        </el-form-item>
      </div>
      <div v-else-if="nodeProps.approvalCategory === ApproveCategory.组织控件关联角色">
        <el-form-item label="选择组织控件" prop="text" class="approve-end">
          <template #label>
            <span class="ikflow-flow-config-label">选择组织控件</span>
          </template>
          <div class="flex flex-col w-full">
            <el-select
              v-model="nodeProps.formOrg"
              clearable
              style="width: 80%;"
              placeholder="请选择包含组织控件的表单项"
            >
              <el-option
                v-for="(op, index) in formOrgs"
                :key="index"
                :label="op.title"
                :value="op.id"
              />
            </el-select>
            <div class="flex flex-col w-[80%]">
              <el-button
                :icon="Plus"
                class="mt-[8px]"
                type="primary"
                @click="selectRole"
              >
                选择角色
              </el-button>
              <OrgItems v-model="nodeProps.assignedUser" />
            </div>
          </div>
        </el-form-item>
      </div>
      <div v-else-if="nodeProps.approvalCategory === ApproveCategory.发起人自己">
        <span class="item-desc">发起人自己作为审批人进行审批</span>
      </div>

      <template v-if="showApproveEmpty">
        <el-divider class="!m-0" />
        <el-form-item label="审批人为空时" prop="text" class="line-mode">
          <template #label>
            <span class="ikflow-flow-config-label">审批人为空时</span>
          </template>
          <el-radio-group v-model="nodeProps.nobody.handler" class="ikflow-flow-radio">
            <el-radio
              v-for="t in state.approval.approvalEmpty"
              :key="t.type"
              :label="t.type"
              class="w-full"
            >
              {{ t.name }}
            </el-radio>
          </el-radio-group>

          <div v-if="nodeProps.nobody.handler === ApprovalEmpty.指定人员审批">
            <OrgItems v-model="nodeProps.reserveApprovals" />
            <el-button
              size="small"
              :icon="Plus"
              type="primary"
              @click="selectNoSetUser"
            >
              选择人员
            </el-button>
          </div>
        </el-form-item>
      </template>

      <div v-if="showMode && nodeProps.approvalCategory !== ApproveCategory.指定成员">
        <el-divider class="!m-0" />
        <el-form-item label="多人审批时审批方式" prop="text" class="approve-mode">
          <template #label>
            <span class="ikflow-flow-config-label">多人审批时审批方式 </span>
          </template>
          <el-radio-group v-model="nodeProps.mode">
            <el-radio :label="MultipleSignature.依次审批" class="w-full">
              依次审批（按顺序依次审批）
            </el-radio>
            <el-radio :label="MultipleSignature.会签" class="w-full">
              会签（须所有审批人同意）
            </el-radio>
            <el-radio :label="MultipleSignature.或签" class="w-full">
              或签（一名审批人同意或拒绝即可）
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <!-- TODO 审批人拒绝后(目前后台不支持) v-if="nodeProps.approvalCategory === ApproveCategory.指定成员" -->
      <template v-if="nodeProps.approvalCategory">
        <el-divider class="!m-0" />
        <el-form-item label="审批人拒绝后">
          <template #label>
            <span class="ikflow-flow-config-label">审批人拒绝后</span>
          </template>
          <!-- <el-radio-group v-model="nodeProps.refuse.type" class="ikflow-flow-radio">
            <el-radio
              :label="ApprovalReject.直接结束"
              class="w-full"
            >
              直接结束
            </el-radio>
            <el-radio label="TO_BEFORE" class="w-full">驳回到上级审批节点</el-radio>
            <el-radio :label="ApprovalReject.退回至指定节点" class="w-full">
              退回至指定节点
            </el-radio>
          </el-radio-group> -->
          <el-radio-group v-model="nodeProps.backToInitiator" class="ikflow-flow-radio">
            <el-radio :label="true" class="w-full">
              退回至发起节点
            </el-radio>
            <el-radio :label="false" class="w-full">
              手动选择退回节点
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- <div v-if="nodeProps.refuse.type === ApprovalReject.手动选择节点"></div> -->
        <!-- <div v-if="!nodeProps.backToInitiator">
          <el-form-item label="指定节点" prop="text">
            <el-select
              v-model="nodeProps.refuse.target"
              style="width: 250px;"
              placeholder="请选择节点"
            >
              <el-option
                v-for="(node, i) in nodeOptions"
                :key="i"
                :label="node.name"
                :value="node.id"
              />
            </el-select>
          </el-form-item>
        </div> -->
      </template>
    </template>
  </el-form>
  <IkingPicker
    ref="refIkingPicker"
    v-model="pickerValue"
    v-model:show="orgPickerShow"
    :title="pickerTitle"
    :multiple="pickState.multiple"
    :tabs="['group', 'role', 'post']"
    :api="{
      methods: 'post',
      url: `${baseUrl}/server/component/pick/mix`,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': token,
      },
    }"
    :choose-type="pickState.chooseType"
    :type-option="{ dep: 'DEPT', user: 'USER', role: 'ROLE', post: 'POST' }"
    :prop-option="{
      name: 'elementName',
      id: 'elementId',
      type: 'elementType',
    }"
    @ok="handSelectPicker"
  />
</template>

<style lang="scss" scoped>
.ikflow-flow-radio {
  label {
    min-width: 130px;
    margin-right: 20px;

    :deep(.el-radio__label) {
      display: flex;
      align-items: center;
    }
  }
}

.ikflow-flow-config-label {
  .info {
    color: var(--el-text-color-secondary);
  }
}

.item-desc{
  color: var(--el-text-color-regular);
  padding: 16px 0;
  display: block;
}
</style>
